package com.batunite.livedatabinding

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import com.batunite.livedatabinding.bean.LevelBean
import com.batunite.livedatabinding.dao.DatabaseHelper
import com.batunite.livedatabinding.databinding.ActivityGameMainBinding
import com.batunite.livedatabinding.views.GameView

/**
 * 游戏主页面
 */
class GameMainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        Log.d(">>>>", "onCreate: ")
        super.onCreate(savedInstanceState)
        val binding = ActivityGameMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val dbHelper = DatabaseHelper(this)
        val gvMain = binding.gvMain
        binding.ivUp.setOnClickListener {
            gvMain.moveUp()
        }

        binding.ivLeft.setOnClickListener {
            gvMain.moveLeft()
        }

        binding.ivRight.setOnClickListener {
            gvMain.moveRight()
        }

        binding.ivRight.setOnLongClickListener(object : View.OnLongClickListener {
            override fun onLongClick(p0: View?): Boolean {
                gvMain.nextLevel()
                return true
            }
        })
        binding.ivDown.setOnClickListener {
            gvMain.moveDown()
        }
        binding.gvMain.setGameStateListener(object : GameView.GameStateListener {
            // 通关当前
            override fun passed(level: Int) {
                Log.d(">>>>", "passed level : $level")
                // level从0开始 数据库id从1开始 下一关+2
                val nextLevel = level + 2
                // 示例：更新 LevelBean 对象
                val queryLevelBean = dbHelper.queryLevelBean(nextLevel)
                if (queryLevelBean != null) {
                    queryLevelBean.completed = true
                    dbHelper.updateLevel(queryLevelBean)
                }
                // 现在是第
                binding.tvTitle.text = "第 $nextLevel 关"
            }

            override fun gameOver() {

            }

            override fun competeAllLevels() {
            }

        })
        binding.ivBack.setOnClickListener{
            binding.gvMain.onBack()
        }
        binding.ivReset.setOnClickListener{
            binding.gvMain.resetData()
        }
        val intExtra = intent.getIntExtra("LEVEL_NUM", 0)
        binding.gvMain.setMap(intExtra)
        binding.tvTitle.text = "第 ${intExtra + 1} 关"
    }


}